﻿using DataAnalyticsTools.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAnalyticsTools.Models
{

    /// <summary>
    /// 簇信息类，描述一个簇的特性和包含的样本
    /// </summary>
    public class Cluster
    {
        public Cluster(int id, float[] centriod)
        {
            ClusterId = id;
            Centroid = centriod;
        }

        /// <summary>
        /// 簇ID（从0开始）
        /// </summary>
        public int ClusterId { get; set; }

        /// <summary>
        /// 簇中心坐标
        /// </summary>
        public float[] Centroid { get; set; } = [];

        /// <summary>
        /// 簇内样本索引列表
        /// </summary>
        public List<int> SampleIndices { get; set; } = [];

        /// <summary>
        /// 簇内样本特征向量（可选，如果需要存储具体样本数据）
        /// </summary>
        public List<float[]> Samples { get; set; } = [];

        /// <summary>
        /// 簇内样本的轮廓系数
        /// </summary>
        public List<float> SilhouetteScores { get; set; } = [];

        /// <summary>
        /// 簇内样本数量
        /// </summary>
        public int SampleCount => SampleIndices?.Count ?? 0;

        /// <summary>
        /// 簇的平均轮廓系数
        /// </summary>
        public float AverageSilhouetteScore => SilhouetteScores?.Any() == true ? SilhouetteScores.Average() : 0f;

        public string ClusteringQuality
        {
            get {
                return AverageSilhouetteScore switch
                {
                    >= 0.7f => "紧密",
                    >= 0.5f => "合理",
                    >= 0.3f => "松散",
                    _ => "分散"
                };
            }
        }

        /// <summary>
        /// 计算簇的半径（最远样本到中心的距离）
        /// </summary>
        public float MaxDistanceToCentroid
        {

            get
            {
                if (Centroid == null || Samples == null || !Samples.Any())
                    return 0f;

                float maxDistance = 0f;
                foreach (var sample in Samples)
                {
                    float distance = MathHelper.EuclideanDistance(Centroid, sample);
                    if (distance > maxDistance)
                        maxDistance = distance;
                }
                return maxDistance;

            }
        }

        /// <summary>
        /// 计算簇内样本到中心的平均距离
        /// </summary>
        public float AverageDistanceToCentroid
        {
            get
            {
                if (Centroid == null || Samples == null || !Samples.Any())
                    return 0f;

                float totalDistance = 0f;
                foreach (var sample in Samples)
                {
                    totalDistance += MathHelper.EuclideanDistance(Centroid, sample);
                }
                return totalDistance / Samples.Count;
            }
        }

    }

}
